package ue.resources;

import java.util.List;
import java.util.Random;

import org.jdom.DataConversionException;
import org.jdom.Element;

public class Deposit {
	
	public static final int LENGTH = Resource.values().length;
	 
	protected int[] resources;
	
	public Deposit(int seed, int[] max) {
		if(max.length != LENGTH) {
			System.err.printf("ERROR: Deposit length not equal to max numbers array length: %d:%d\n", 
					resources.length, LENGTH);
			return;
		}
		
		Random random = new Random(seed);
		resources = new int[LENGTH];
		
		for(int i = 0; i < LENGTH; i++) {
			if(max[i] > 0)
				resources[i] = random.nextInt(max[i]);
		}
	}
	
	public Deposit(int[] resources) {
		if(resources.length != LENGTH) {
			System.err.printf("ERROR: Deposit length not equal: %d:%d\n", 
					resources.length, LENGTH);
			return;
		}
		
		this.resources = resources;
	}
	
	public Deposit() {
		this.resources = new int[LENGTH];
		fillResources();
	}
	
	public Deposit(Element element) {
		if(element.getName() != "deposit") {
			System.err.println("ERROR: Incorrect XML Deposit Element: Wrong element name.");
			System.exit(1);
		}
		
		try {
			if(element.getAttribute("length").getIntValue() != LENGTH) {
				System.err.println("ERROR: Incorrect XML Deposit Element: Wrong resource length.");
				System.exit(1);
			}
		} catch (DataConversionException e) {
			e.printStackTrace();
		}
		
		this.resources = new int[LENGTH];
		
		List<?> resourceList = element.getChildren("resource");
		
		for(int i = 0; i < resourceList.size(); i++) {
			try {
				resources[((Element)resourceList.get(i)).getAttribute("index").getIntValue()] = Integer.parseInt(((Element)resourceList.get(i)).getText());
			} catch (NumberFormatException e) {
				e.printStackTrace();
			} catch (DataConversionException e) {
				e.printStackTrace();
			}
		}
	}
	
	protected void fillResources() {
		for(int i = 0; i < resources.length; i++) {
			resources[i] = 0;
		}
	}
	
	public int getResource(int resource) {
		return resources[resource];
	}
	
	public int extract(int resource, int amount) {
		if(amount <= 0) return 0;
		
		resources[resource] -= amount;
		
		int newAmount = amount;
		
		if(resources[resource] < 0) {
			newAmount += resources[resource];
			resources[resource] = 0;
		}
		
		return newAmount;
	}
	
	@Override
	public String toString() {
		String tmp = "";
		
		for(int i = 0; i < LENGTH; i++) {
			tmp += i + ":" + resources[i] + "; ";
		}
		
		return tmp.trim();
	}
	
	public Element toXMLElement() {
		Element element = new Element("deposit");
		element.setAttribute("length", "" + LENGTH);
		
		for(int i = 0; i < LENGTH; i++) {
			Element resourceElement = new Element("resource");
			resourceElement.setAttribute("index", "" + i);
			resourceElement.setText("" + resources[i]);
			
			element.addContent(resourceElement);
		}
		
		return element;
	}
}
